<?php

namespace Tests;

use Illuminate\Database\MySqlConnection;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\DB;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    /**
     * @throws \Exception
     */
    protected function setUp()
    {
        $this->initApp();
        $this->checkTestingEnvFile();
        $this->checkDatabaseUserName();

        parent::setUp();
    }

    /**
     * 测试确认使用 .env.testing 文件
     *
     * @throws \Exception
     */
    private function checkTestingEnvFile(): void
    {
        if(! is_file(base_path('.env.testing'))) {
            echo('You Should create .env.testing for PhpUnit test');
            exit(1);
        };

        if (config('app.env') !== 'testing') {
            echo('You Should use .env.testing for PhpUnit test');
            exit(1);
        }
    }

    /**
     * @throws \Exception
     */
    private function checkDatabaseUserName()
    {
        /** @var MySqlConnection $conn */
        $conn = DB::connection();
        $env_name = $conn->getConfig()['username'];
        $test_name = 'dev'; // 测试数据库
//        $test_name = 'beauty_mirror'; // 生产数据库

        if($env_name !== $test_name) {
            echo("You database username is [$env_name], should be [$test_name] for PhpUnit test");
            exit(1);
        };
    }

    protected function initApp(): void
    {
        if (! $this->app) {
            $this->refreshApplication();
        }
    }
}
